import { defineStore } from 'pinia';

/**
 * 创建并导出字典存储的 Vue3 store 对象
 * @function
 * @returns {DictionaryStore} - 返回创建的字典存储对象
 */
export const useSetting = defineStore('setting', {
  state: () => ({
    rootFontSize: uni.getStorageSync('fontSize') || '16px',
	bluetoothDevices:[],
	connected:false,
	currentDevice:'',
	devices:[],
	brainDevices:[],
	isNotify:false,
	currentBrain:null
  }),
  actions: {
    setRootFontSize(value: string) {
      if (!value || typeof value !== 'string') {
        return;
      }
      this.rootFontSize = value;
    },
	setConnect(value: boolean) {
	  this.connected = value;
	},
	setBluetoothDevices() {
	   uni.onBluetoothDeviceFound((res)=>{
		   if (this.connected  || !res.devices[0].name) return;
		   // 过滤重复
		   const device = this.bluetoothDevices.find((device:any) => device.name === res.devices[0].name);
		   if (!device) {
			 this.bluetoothDevices.push(res.devices[0]) 
		   }
	   });
	   uni.onBLEConnectionStateChange((res) => {
	     if (res.connected) {
	       this.connected = true;
	       this.currentDevice = res.deviceId;
	     } else {
	       uni.closeBLEConnection({
	         deviceId: res.deviceId,
	       });
	        this.connected = false;
	        this.currentDevice = '';
	       // printModule.closePort();
	     }
	   });
	},
	onDevice() {
	  uni.onBluetoothDeviceFound((devices)=> {
			var re = JSON.parse(JSON.stringify(devices))
			console.log(re);
			const {name,deviceId} = re.devices[0];
			if (name != "未知设备" &&  name && !this.devices.find(d=>d.deviceId === deviceId )) {
				this.devices.push({
					name,
					deviceId,
					services: []
				})
			}	
	  })
	},
	onBrainDevices() {
	  uni.onBluetoothDeviceFound((devices)=> {
			var re = JSON.parse(JSON.stringify(devices))
			const {name,deviceId} = re.devices[0];
			if (name != "未知设备" &&  name && !this.brainDevices.find(d=>d.deviceId === deviceId )) {
				this.brainDevices.push({
					name,
					deviceId,
					services: []
				})
			}	
	  })
	}
  },
});
